import { acceptHMRUpdate, defineStore } from "pinia";
import { useLocalRef } from "@/framework/vue/hooks/state.ts";
import { ref, watch } from "vue";
import { mitt } from "@/framework/util/event-emitter.ts";
import path from "@/framework/util/path.ts";

/**
 * 设置事件
 */
export const SettingsEvents = mitt<{
  /**
   * 开发环境安装路径改变
   */
  "dev-install-path-changed": string;
  /**
   * 数据库安装路径改变
   */
  "database-install-path-changed": string;
}>();

const getDefaultDownloadDir = () => path.join(native.process.env.USERPROFILE!, "Downloads/DevilBox");

/**
 * 设置
 */
export const useSettingStore = defineStore("settings", () => {
  /**
   * 模态框打开状态
   */
  const modalOpen = ref(false);

  /**
   * 下载目录
   */
  const downloadDir = useLocalRef("download.dir", getDefaultDownloadDir);

  /**
   * 获取下载路径
   * @param rpath 相对于下载目录的路径
   */
  const getDownloadPath = (rpath: string) => {
    const root = downloadDir.value || getDefaultDownloadDir();
    return path.join(root, rpath);
  };

  /**
   * 开发环境安装路径
   */
  const devInstallPath = useLocalRef("install.path.dev", "C:\\Dev\\env");
  watch(devInstallPath, value => SettingsEvents.emit("dev-install-path-changed", value));

  /**
   * 数据库安装路径
   */
  const databaseInstallPath = useLocalRef("install.path.database", "C:\\Dev\\database");
  watch(databaseInstallPath, value => SettingsEvents.emit("database-install-path-changed", value));

  /**
   * 安装成功后删除安装包
   */
  const deletePackageAfterInstall = useLocalRef("delete.package.after.install", true);
  /**
   * PostgreSQL: 安装后删除pgAdmin
   */
  const pgDeletePgAdmin = useLocalRef("pg.deletePgAdmin", true);

  return {
    modalOpen: modalOpen,

    downloadDir: downloadDir,
    getDownloadPath: getDownloadPath,
    devInstallPath: devInstallPath,
    databaseInstallPath: databaseInstallPath,
    deletePackageAfterInstall: deletePackageAfterInstall,
    pgDeletePgAdmin: pgDeletePgAdmin,
  };
});

if (import.meta.hot) {
  import.meta.hot.accept(acceptHMRUpdate(useSettingStore, import.meta.hot));
}
